package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.shop.enums.ShopMessageEnum;
import com.qys.livesMall.shop.modal.dto.PurchaseAccountUse;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.entity.H2ShopLevel;
import com.qys.livesMall.shop.modal.entity.ShopPurchaseAccount;
import com.qys.livesMall.shop.mapper.ShopPurchaseAccountMapper;
import com.qys.livesMall.shop.service.H2ShopBaseService;
import com.qys.livesMall.shop.service.H2ShopLevelService;
import com.qys.livesMall.shop.service.ShopPurchaseAccountRecordService;
import com.qys.livesMall.shop.service.ShopPurchaseAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 采购额度账户 服务实现类
 * </p>
 *
 * @author
 * @since 2023-09-15
 */
@Service
public class ShopPurchaseAccountServiceImpl extends ServiceImpl<ShopPurchaseAccountMapper, ShopPurchaseAccount> implements ShopPurchaseAccountService {

    @Autowired
    private H2ShopBaseService h2ShopBaseService;

    @Autowired
    private H2ShopLevelService shopLevelService;

    @Autowired
    private ShopPurchaseAccountRecordService shopPurchaseAccountRecordService;

    public ShopPurchaseAccount build(Long userId){
        synchronized (userId){
            String mouth=DateUtils.parseMouthDateNow();
            LambdaQueryWrapper<ShopPurchaseAccount> qw=new LambdaQueryWrapper<>();
            qw.eq(ShopPurchaseAccount::getUserId,userId);
            qw.eq(ShopPurchaseAccount::getEffectiveMonth,mouth);
            qw.last("limit 1");
            ShopPurchaseAccount account=getOne(qw);
            if (account!=null){
                return account;
            }
            H2ShopBase shop=h2ShopBaseService.queryShopBaseByUserId(userId);
            if (shop==null){
                return null;
            }
            H2ShopLevel level=shopLevelService.getById(shop.getShopLevelId());
            if (level==null){
                throw new QysException(ShopMessageEnum.SHOP_BASE_LEVEL_ERROR);
            }
            BigDecimal quota=level.getPurchaseQuota();
            if (level.getPurchaseQuota()==null){
                quota=new BigDecimal("10000");
            }
            account=new ShopPurchaseAccount();
            account.setShopId(shop.getId());
            account.setUserId(userId);
            account.setPurchaseAmount(quota);
            account.setTotalPurchaseAmount(quota);
            account.setEffectiveMonth(mouth);
            account.setUpdateTime(LocalDateTime.now());
            save(account);
            return account;

        }
    }

    @Override
    public ShopPurchaseAccount getByUserId(Long userId) {
        return build(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PurchaseAccountUse upgradeUp(H2ShopBase shop) {
        PurchaseAccountUse use=new PurchaseAccountUse();
        use.setStatus(false);
        if (shop==null){
            return use.setMessage(ShopMessageEnum.SHOP_NOT_EXIST);
        }
        synchronized (shop.getUserId()){
            ShopPurchaseAccount account=build(shop.getUserId());
            //获取等级
            H2ShopLevel level=shopLevelService.getById(shop.getShopLevelId());
            if (level==null){
               return use.setMessage(ShopMessageEnum.SHOP_BASE_LEVEL_ERROR);
            }
            BigDecimal quota=level.getPurchaseQuota();
            if (level.getPurchaseQuota()==null){
                quota=new BigDecimal("10000");
            }
            BigDecimal useQuota=account.getTotalPurchaseAmount().subtract(account.getPurchaseAmount());
            account.setTotalPurchaseAmount(quota.add(useQuota));
            account.setPurchaseAmount(quota);
            account.setUpdateTime(LocalDateTime.now());
            updateById(account);
            //记录
            use.setAccountId(account.getId());
            use.setType(2);
            use.setUseAmount(new BigDecimal("0"));
            use.setUserId(account.getUserId());
            use.setShopId(account.getShopId());
            use.setAfter(account.getPurchaseAmount());
            shopPurchaseAccountRecordService.add(use);
            use.setStatus(true);
            return use;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void purchaseOut(PurchaseAccountUse use) {
        use.setStatus(false);
        if (use==null||use.getUserId()==null||use.getUseAmount()==null){
            use.setMessage(ExceptionEnum.PARAM_IS_ERROR);
            return;
        }
        synchronized (use.getUserId()){
            ShopPurchaseAccount account=build(use.getUserId());
            BigDecimal amount=account.getPurchaseAmount().subtract(use.getUseAmount());
            if (amount.compareTo(new BigDecimal("0"))<0){
                use.setMessage(ShopMessageEnum.SHOP_PURCHASE_AMOUNT_INSUFFICIENT);
                return;
            }
            account.setPurchaseAmount(amount);
            account.setTotalUsePurchaseAmount(account.getTotalUsePurchaseAmount().add(amount));
            account.setUpdateTime(LocalDateTime.now());
            updateById(account);
            //记录
            use.setType(1);
            use.setAfter(account.getPurchaseAmount());
            use.setAccountId(account.getId());
            shopPurchaseAccountRecordService.add(use);
            use.setStatus(true);
        }
    }


}
